package com.epoch.platform.sys.role.controller;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.util.AjaxResult;
import com.epoch.platform.sys.menu.service.SysMenuService;
import com.epoch.platform.sys.role.dao.SysRole;
import com.epoch.platform.sys.role.service.SysRoleService;
import com.epoch.platform.sys.rolemenu.dao.SysRoleMenu;
import com.epoch.platform.sys.userrole.dao.SysUserRole;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/role")
public class SysRoleController extends BaseController{
	
	SysRoleService sysRoleService = new SysRoleService();
	
	private AjaxResult ajaxResult = new AjaxResult();
	
	private SysMenuService sysMenuService = new SysMenuService();
	
	public void index() {
		this.render("/sys/role/sys_role_tab.html");
	}
	
	public void listUI() {
		this.render("/sys/role/sys_role_list.html");
	}
	
	public void findRoleListAjax() {
        Kv param = commonParams();
        SqlPara sqlPara = Db.getSqlPara("systemManage.findSysRole", param);
        Page<SysRole> roleList = SysRole.dao.paginate(sqlPara, param);
        renderJson(roleList);
    }
	
	public void findRoleForUser() {
        Kv param = commonParams();
        String roleType = getPara("roleType");
        param.put("roleType", roleType);
        SqlPara sqlPara = Db.getSqlPara("systemManage.selectRoleForUser", param);
        Page<SysRole> roleList = SysRole.dao.paginate(sqlPara, param);
        renderJson(roleList);
    }
	
	public void suvUI() {
        String id = getPara("ID");
        SysRole sysRole;
        if (StringUtils.isNotBlank(id)) {
            sysRole = SysRole.dao.findById(id);
        } else {
            sysRole = new SysRole();
        }
        setAttr("menuTree", JsonKit.toJson(sysMenuService.getAllTreeMenuList(Kv.by("status", "ENABLE"))));
        SysRoleMenu roleMenu = SysRoleMenu.dao.findFirst(Db.getSql("systemManage.findSysMenuByRoleId"), id);
        sysRole.put("menuRole", roleMenu != null ? roleMenu.getStr("menuRole") : "");
        setAttr("menuRoleShow", roleMenu != null && roleMenu.getStr("menuRoleShow")!=null ? roleMenu.getStr("menuRoleShow").replaceAll(",","\r\n") : "");
        setAttr("SysRole", sysRole);
        render("/sys/role/sys_role_edit.html");
    }
	
	public void suv() {
        try {
            SysRole sysRole = getModel(SysRole.class, "SysRole");
            if (sysRole != null) {
            	List<SysRole> verifyRoleList = SysRole.dao.find(Db.getSqlPara("systemManage.findSysRoleOne", Kv.by("role_name", sysRole.get("role_name"))
                        .set("role_code", sysRole.get("role_code"))));
            	if (CollectionUtils.isEmpty(verifyRoleList) || sysRole.get("ID") != null) {
            		sysRole.saveOrUpdate();
                    String roleId = sysRole.getStr(SysRole.ID);
                  //保存对应的角色信息
                    Db.update(Db.getSql("systemManage.deleteRoleMenuByRoleId"), roleId);
                    //3.获取角色选择的菜单ID数组
                    String idsStr = getPara("menuRole", null);
                    if (StringUtils.isNotBlank(idsStr)) {
                        String[] menuIds = idsStr.split(",");
                        //4.重新保存角色现有菜单
                        for (String menuId : menuIds) {
                        	SysRoleMenu roleMenu = new SysRoleMenu();
                            roleMenu.set(SysRoleMenu.MENU_ID, menuId);
                            roleMenu.set(SysRoleMenu.ROLE_ID, roleId);
                            roleMenu.save();
                        }
                    }
                    renderJson(ajaxResult.success("保存成功"));
            	}
            }
        }catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
     * 删除的方法
     */
    public void delete() {
        String[] ids = getParaValues("ids[]");
        AjaxResult ajaxResult = new AjaxResult();
        SysRole deleteRole = new SysRole();
        try {
            if (ids.length > 0) {
                for (String id : ids) {
                    deleteRole.deleteById(id);
                    //通过角色id查找角色_菜单列表和用户_角色列表
                    List<SysUserRole> userRoles = SysUserRole.dao.find("SELECT * FROM SYS_USER_ROLE WHERE ROLE_ID=?", new Object[]{id});
                    if (CollectionUtils.isNotEmpty(userRoles)) {
                        for (SysUserRole userRole : userRoles) {
                            userRole.delete();
                        }
                    }
                    List<SysRoleMenu> list = SysRoleMenu.dao.find("SELECT * FROM SYS_ROLE_MENU WHERE ROLE_ID=?", new Object[]{id});
                    //遍历删除
                    if (list != null && list.size() > 0) {
                        for (SysRoleMenu roleMenu : list) {
                            roleMenu.delete();
                        }
                    }
                }
                ajaxResult.success("删除成功。");
            }
        } catch (Exception e) {
            ajaxResult.addError("删除失败。");
        }
        redirect("/sys/role");
    }

}
